import {Game_login} from "../types/clientType";
import {GamesModel} from "../models/gamesModel";
import {getNewToken, getToken} from "./tokenService";

require('express-async-errors')

export async function handlerGame(data: Game_login) {
    const db_data: any = await GamesModel.findOne({appid: data.appid});
    await updateGame(data, db_data);
    if (!db_data) {
        const token = await getNewToken(data.appid, data.secret);
        const new_game = new GamesModel({
            appid: data.appid, secret: data.secret, name: data.name, token: token
        });
        await new_game.save();
        return GamesModel.findOne({appid: data.appid});
    } else if (!db_data.token.access_token || !db_data.token) {
        const token = await getToken(data.appid, data.secret);
        await GamesModel.updateOne({appid: data.appid}, {$set: {token: token}});
        return GamesModel.findOne({appid: data.appid});
    } else {
        return db_data;
    }
}

export async function updateGame(data: any, db_data: any) {
    if (!db_data) return;
    if (data.name !== db_data.name || data.secret !== db_data.secret) {
        await GamesModel.updateOne({appid: data.appid}, {$set: {name: data.name, secret: data.secret}});
    }
}